package com.ruoyi.tb.lmt.controller;

import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.tb.lmt.domain.bo.TbMessageNoticeBo;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanlistBo;
import com.ruoyi.tb.lmt.service.ITbMessageNoticeService;
import com.ruoyi.tb.lmt.service.ITbRepairplanlistService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbRepairplanlistApprovedVo;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanlistApprovedBo;
import com.ruoyi.tb.lmt.service.ITbRepairplanlistApprovedService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * //大机报告申请
 *
 * @author ruoyi
 * @date 2024-04-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/repairplanlistApproved")
public class TbRepairplanlistApprovedController extends BaseController {

    private final ITbRepairplanlistApprovedService iTbRepairplanlistApprovedService;

    @Autowired
    private ITbRepairplanlistService iTbRepairplanlistService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ITbMessageNoticeService iTbMessageNoticeService;

    /**
     * 查询//大机报告申请列表
     */
    @GetMapping("/list")
    public TableDataInfo<TbRepairplanlistApprovedVo> list(TbRepairplanlistApprovedBo bo, PageQuery pageQuery) {
        return iTbRepairplanlistApprovedService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出//大机报告申请列表
     */
    @Log(title = "//大机报告申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbRepairplanlistApprovedBo bo, HttpServletResponse response) {
        List<TbRepairplanlistApprovedVo> list = iTbRepairplanlistApprovedService.queryList(bo);
        ExcelUtil.exportExcel(list, "//大机报告申请", TbRepairplanlistApprovedVo.class, response);
    }

    /**
     * 获取//大机报告申请详细信息
     *
     * @param ID 主键
     */
    //@SaCheckPermission("xha-lmt:repairplanlistApproved:query")
    @GetMapping("/{ID}")
    public R<TbRepairplanlistApprovedVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long ID) {
        return R.ok(iTbRepairplanlistApprovedService.queryById(ID));
    }

    /**
     * 新增//大机报告申请
     */
    //@SaCheckPermission("xha-lmt:repairplanlistApproved:add")
    @Log(title = "//大机报告申请", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbRepairplanlistApprovedBo bo) {
        return toAjax(iTbRepairplanlistApprovedService.insertByBo(bo));
    }

    /**
     * 修改//大机报告申请
     */
    //@SaCheckPermission("xha-lmt:repairplanlistApproved:edit")
    @Log(title = "//大机报告申请", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbRepairplanlistApprovedBo bo) {
        return toAjax(iTbRepairplanlistApprovedService.updateByBo(bo));
    }

    /**
     * 删除//大机报告申请
     *
     * @param IDs 主键串
     */
    //@SaCheckPermission("xha-lmt:repairplanlistApproved:remove")
    @Log(title = "//大机报告申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] IDs) {
        return toAjax(iTbRepairplanlistApprovedService.deleteWithValidByIds(Arrays.asList(IDs), true));
    }

    /**
     * 设备科通过大机报告申请
     */
    @SaCheckPermission("xha-lmt:repairplanlistApproved:equipmentApprove")
    @PutMapping("/equipmentApprove")
    public R<Void> equipmentApprove(@Validated(EditGroup.class) @RequestBody TbRepairplanlistApprovedBo bo) {
        String username = LoginHelper.getLoginUser().getUsername();

        // 检查当前用户是否是设备科或管理员
        if (!isUserInEquipmentDepartment(username) && !isAdmin(username)) {
            throw new IllegalArgumentException("您没有权限审批该申请");
        }

        bo.setApprovedStatus("验收室审批中");
        bo.setApprovedUser(LoginHelper.getUsername());
        bo.setApprovedTime(new Date());
        //设置审批人为验收室负责人
        bo.setApprovedUser2(iTbMessageNoticeService.getAcceptanceRoom());


        LoginUser currentUser =  LoginHelper.getLoginUser();
        //发送消息通知
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        messageNoticeBo.setMessageId(bo.getApprovedId());
        messageNoticeBo.setMessageTitle(bo.getLmtNumber()+"申请履历报告");
        messageNoticeBo.setMessageName(currentUser.getUsername()+"申请"+bo.getLmtNumber()+"大机的履历报告，请及时处理。");
        messageNoticeBo.setMessageType("申请履历报告");
        messageNoticeBo.setLmtType(bo.getLmtType());
        messageNoticeBo.setLmtNumber(bo.getLmtNumber());
        messageNoticeBo.setWorkGroup(currentUser.getDeptName());
        messageNoticeBo.setWorkUser(currentUser.getUsername());
        messageNoticeBo.setWorkerTeam(bo.getWorkerTeam());
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setWorkGroupId(bo.getWorkGroupId());
        messageNoticeBo.setWorkTime(new Date());
        //设置接收人为验收室负责人
        messageNoticeBo.setRecipient(iTbMessageNoticeService.getAcceptanceRoom());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);

        return toAjax(iTbRepairplanlistApprovedService.updateByBo(bo));
    }

    public boolean isUserInEquipmentDepartment(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有设备科的角色标识
        for (SysRole role : userRoles) {
            if ("equipmentDept".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }
    public boolean isAdmin(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有管理员角色
        for (SysRole role : userRoles) {
            if ("admin".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }


    /**
     * 验收室通过大机报告申请
     */
    @SaCheckPermission("xha-lmt:repairplanlistApproved:acceptanceRoomApproved")
    @PutMapping("/acceptanceRoomApproved")
    public R<Void> acceptanceRoomApproved(@Validated(EditGroup.class) @RequestBody TbRepairplanlistApprovedBo bo) {

        String username = LoginHelper.getLoginUser().getUsername();

        if (!isUserInAcceptanceRoom(username) && !isAdmin(username)) {
            throw new IllegalArgumentException("您没有权限审批该申请");
        }

        bo.setApprovedStatus("已通过");
        //重新设置验收室实际审批人
        bo.setApprovedUser2(LoginHelper.getUsername());
        bo.setApprovedTime2(new Date());

        //修改明细表内容
        TbRepairplanlistBo tbRepairplanlistBo = new TbRepairplanlistBo();
        tbRepairplanlistBo.setId(bo.getApprovedId());
        tbRepairplanlistBo.setApprovedStatus("已审批");
        tbRepairplanlistBo.setApprovedTime(new Date());
        tbRepairplanlistBo.setApprovedUser(bo.getApprovedUser());
        iTbRepairplanlistService.updateByBo(tbRepairplanlistBo);
        return toAjax(iTbRepairplanlistApprovedService.updateByBo(bo));
    }

    public boolean isUserInAcceptanceRoom(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有验收室的角色标识
        for (SysRole role : userRoles) {
            if ("acceptanceRoom".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查询//大机报告申请列表
     */
    @GetMapping("/applyList")
    public TableDataInfo<TbRepairplanlistApprovedVo> applyList(PageQuery pageQuery) {
        return iTbRepairplanlistApprovedService.selectApplyList(pageQuery);
    }

}
